using System.Collections.Generic;
using UnityEngine.UIElements;

namespace DA.AnimGraph.Editor {

    internal abstract class NonContextPaneBase : VisualElement {

        protected readonly AGEEnvironment ageEnv;
        private List<NonContextPaneBase> childrenPane;
        protected NonContextPaneBase parentPane { get; private set; }
        protected virtual bool isValid { get => isValidInternal; }
        private bool isValidInternal;
        protected NonContextPaneBase(AGEEnvironment ageEnv) {
            isValidInternal = false;
            this.ageEnv = ageEnv;
        }

        protected NonContextPaneBase(NonContextPaneBase parent) {
            isValidInternal = false;
            ageEnv = parent.ageEnv;
            AttachToParent(parent);
        }

        public virtual void Init() {
            if (isValid) {
                isValidInternal = false;
                OnClearUI();
            }
            isValidInternal = true;
            OnDrawUI();
        }

        private void AttachToParent(NonContextPaneBase parent) {
            parentPane = parent;
            if (parent.childrenPane == null) {
                parent.childrenPane = new List<NonContextPaneBase>();
            }
            parent.childrenPane.Add(this);
        }

        /// <summary>
        /// 调用子节点以及自己的 OnUpdateUI
        /// </summary>
        public void Update() {
            if (childrenPane != null) {
                foreach (var child in childrenPane) {
                    child.Update();
                }
            }
            if (isValid) {
                OnUpdateUI();
            }
        }

        /// <summary>
        /// 调用子节点以及自己的 OnClearUI
        /// </summary>
        public void Close() {
            if (childrenPane != null) {
                foreach (var child in childrenPane) {
                    child.Close();
                }
            }
            OnClearUI();
            // todo：从父节点中移除
        }

        public void Open() {
            // todo:打开并添加为子节点，但是不负责Init
        }

        protected abstract void OnDrawUI();
        protected abstract void OnClearUI();
        protected virtual void OnUpdateUI() { }
    }

}
